package com.sdkj.fixed.asset.assets.service;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.sdkj.fixed.asset.api.assets.in_vo.report.*;
import com.sdkj.fixed.asset.api.assets.out_vo.report.*;
import com.sdkj.fixed.asset.api.login.pojo.LoginUser;
import com.sdkj.fixed.asset.assets.mapper.ReportMapper;
import com.sdkj.fixed.asset.assets.util.ExcelStyle;
import com.sdkj.fixed.asset.common.base.BaseResultVo;
import com.sdkj.fixed.asset.common.base.PageParams;
import com.sdkj.fixed.asset.common.exception.LogicException;
import com.sdkj.fixed.asset.pojo.system.UserManagement;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;

/**
 * @ClassName ReportService
 * @Description TODO
 * @Author 张欣
 * @Date 2020/7/30 16:37
 */
@Service
public class ReportService {
    @Autowired
    private ReportMapper reportMapper;
    private static Logger log = LoggerFactory.getLogger(WarehouseService.class);
    /**
     * 查询资产清单
     *
     * @param pageParams
     * @return
     */
    public List<AssetListReport> getPageAssetList(PageParams<AssetListParam> pageParams, LoginUser loginUser) {

        String userId = loginUser.getUserId();
        Integer isAllDataAuth = reportMapper.selectUserIsAllDataAuth(userId);
        AssetListParam params = pageParams.getParams();
        //参数
        Map<String, Object> param = new HashMap<>();
        param.put("userId", userId);

        //是否有全部权限
        param.put("isAllDataAuth", Integer.toString(isAllDataAuth));
        param.put("TopCompanyId", loginUser.getCompanys().get(0).getCompanyId());
        if (params != null) {
            param.put("useCompanyId", params.getUseCompanyId());
            param.put("search", params.getSearch());
        }
        //如果没有全部权限查询各数据的权限
        if (isAllDataAuth == 2) {
            getUserAuth(userId, param);
        }
        PageHelper.startPage(pageParams.getCurrentPage(), pageParams.getPerPageTotal());
        List<AssetListReport> AssetList = reportMapper.getPageAssetList(param);
        for (AssetListReport entity : AssetList) {
            handleAssetListResult(entity);
        }
        return AssetList;
    }

    //处理资产清单结果数据，查询结果code拼接在name
    private void handleAssetListResult(AssetListReport entity) {
        //设置区域
        String areaName = entity.getAreaName();
        if (StrUtil.isNotBlank(areaName)) {
            String[] areas = areaName.split("-");
            entity.setAreaCode(areas[0]);
            entity.setAreaName(areas[1]);
        }
        //设置类别
        String assetClassName = entity.getAssetClassName();
        if (StrUtil.isNotBlank(assetClassName)) {
            String[] classNames = assetClassName.split("/");
            StringBuilder classCode = new StringBuilder();
            StringBuilder className = new StringBuilder();
            for (String str : classNames) {
                String[] split = str.split("-");
                classCode.append("-" + split[0]);
                className.append("/" + split[1]);
            }
            entity.setAssetClassCode(classCode.toString().replaceFirst("-", ""));
            entity.setAssetClassName(className.toString().replaceFirst("/", ""));
        }
        //设置使用公司
        String areaUseCompany = entity.getUseCompanyName();
        if (StrUtil.isNotBlank(areaUseCompany)) {
            String[] areaUseCompanys = areaUseCompany.split("-");
            entity.setUseCompanyCode(areaUseCompanys[0]);
            entity.setUseCompanyName(areaUseCompanys[1]);
        }
        //设置使用部门
        String areaUseDept = entity.getUseDeptName();
        if (StrUtil.isNotBlank(areaUseDept)) {
            String[] UseDepts = areaUseDept.split("-");
            entity.setUseDeptCode(UseDepts[0]);
            entity.setUseDeptName(UseDepts[1]);
        }
        //设置所属公司
        String company = entity.getCompanyName();
        if (StrUtil.isNotBlank(company)) {
            String[] companys = company.split("-");
            entity.setCompanyCode(companys[0]);
            entity.setCompanyName(companys[1]);
        }
    }

    /**
     * 组装用户权限数据
     *
     * @param userId
     * @param param
     */
    private void getUserAuth(String userId, Map<String, Object> param) {
        //公司
        List<String> orgAuth = reportMapper.selectCompanyOrDeptAuth(userId, 1);
        if (orgAuth.size() > 0) {
            param.put("orgAuth", orgAuth);
        }
        //部门
        List<String> deptAuth = reportMapper.selectCompanyOrDeptAuth(userId, 2);
        if (deptAuth.size() > 0) {
            param.put("deptAuth", deptAuth);
        }
        //类别
        List<String> classAuth = reportMapper.selectUserAuth(userId, 2);
        if (classAuth.size() > 0) {
            param.put("classAuth", classAuth);
        }
        //区域
        List<String> areaAuth = reportMapper.selectUserAuth(userId, 3);
        if (areaAuth.size() > 0) {
            param.put("areaAuth", areaAuth);
        }
        //仓库
        List<String> wareHouseAuth = reportMapper.selectUserAuth(userId, 4);
        if (wareHouseAuth.size() > 0) {
            param.put("wareHouseAuth", wareHouseAuth);
        }
    }

    /**
     * 查询处理记录
     *
     * @param assetId
     * @return
     */
    public AssetHandleRecord viewAssetHandleRecord(AssetId assetId) {
        List<AssetHandleRecord> assetHandleRecords = reportMapper.viewAssetHandleRecord(assetId);
        if (assetHandleRecords.size() == 0) {
            return new AssetHandleRecord();
        }
        return assetHandleRecords.get(0);
    }

    /**
     * 导出查询
     *
     * @param useCompanyId
     * @param search
     * @param loginUserId
     * @return
     */
    public List<AssetListReport> getExportData(String useCompanyId, String search, String loginUserId) {

        List<UserManagement> userManagements = reportMapper.selectUser(loginUserId);
        if (userManagements.size() == 0) {
            throw new LogicException("用户不存在");
        }
        UserManagement userManagement = userManagements.get(0);
        Integer isAllDataAuth = userManagement.getDataIsAll();
        //参数
        Map<String, Object> param = new HashMap<>();
        param.put("userId", loginUserId);

        //是否有全部权限
        param.put("isAllDataAuth", Integer.toString(isAllDataAuth));
        param.put("TopCompanyId", userManagement.getTopCompanyId());
        param.put("useCompanyId", useCompanyId);
        param.put("search", search);
        //如果没有全部权限查询各数据的权限
        if (userManagement.getDataIsAll() == 2) {
            getUserAuth(loginUserId, param);
        }
        List<AssetListReport> AssetList = reportMapper.exportQuery(param);
        for (AssetListReport entity : AssetList) {
            handleAssetListResult(entity);
        }
        return AssetList;
    }

    /**
     * 查询资产履历
     *
     * @param params
     * @param loginUser
     * @return
     */
    public List<AssetHandleRecords> getPageAssetHandleRecord(AssetHandleRecordParam params, Integer pageNo,Integer pageSize, LoginUser loginUser) {

        String userId = loginUser.getUserId();
        Integer isAllDataAuth = reportMapper.selectUserIsAllDataAuth(userId);
        //参数
        Map<String, Object> param = new HashMap<>();
        param.put("userId", userId);
        //是否有全部权限
        param.put("isAllDataAuth", Integer.toString(isAllDataAuth));
        param.put("TopCompanyId", loginUser.getCompanys().get(0).getCompanyId());
        if (params != null) {
            param.put("startTime", params.getStartTime());
            param.put("endTime", params.getEndTime());
        }
        //如果没有全部权限查询各数据的权限
        if (isAllDataAuth == 2) {
            getUserAuth(userId, param);
        }
        if(pageNo != null && pageSize != null){
            PageHelper.startPage(pageNo, pageSize);
        }
        List<AssetHandleRecords> pageAssetHandleRecord = reportMapper.getPageAssetHandleRecord(param);
        //查询处理记录详情
        for (AssetHandleRecords record : pageAssetHandleRecord) {
            record.setAssetHandleRecordDetaileds(reportMapper.getAssetHandleRecordDetail(record.getAssetId()));
        }
        return pageAssetHandleRecord;
    }

    /**
     * 导出资产履历
     * @param params
     * @param loginUser
     * @return
     */
    public HSSFWorkbook exportAssetHandleRecords(AssetHandleRecordParam params,LoginUser loginUser){
        List<AssetHandleRecords> assetHandleRecord = getPageAssetHandleRecord(params,null,null,loginUser);

        //列表数据
        Map<String, Object> rowsDataAndMergeRow = buildRows(assetHandleRecord);
        Map<String,String> statistics =(Map<String,String>) rowsDataAndMergeRow.get("statistics");
        String title = "资产履历";
        String sheetName = "资产履历";

        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFRow row = null;
        HSSFCell cell = null;
        //行
        int rownum = 0;
        // 建立新的sheet对象（excel的表单） 并设置sheet名字
        HSSFSheet sheet = wb.createSheet(sheetName);
        sheet.setDefaultColumnWidth(18);
        sheet.setDefaultRowHeight((short) 512);
        // 在sheet里创建第一行，参数为行索引(excel的行)，可以是0～65535之间的任何一个
        row = sheet.createRow(rownum++);
        row.setHeight((short) 1000 );
        // 创建单元格（excel的单元格，参数为列索引，可以是0～255之间的任何一个
        cell = row.createCell(0);
        // 合并单元格CellRangeAddress构造参数依次表示起始行，截至行，起始列， 截至列
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 22));
        cell.setCellValue(title);
        cell.setCellStyle(ExcelStyle.styleTitle(wb));
        String[] row1 = {"资产总数:", "", "资产总额:", "","正常在用资产:", "","已清理:",""};
        String[] row2 = {statistics.get("assetTotal"), "", statistics.get("totalAmount"), "",statistics.get("assetNormalTotal"), "",statistics.get("clearAsset"),""};
        String[] row3 = {"", "", "", "","", "","",""};
        String[] row4= {"状态", "照片", "资产条码", "资产名称","资产类别", "规格型号","SN号","计量单位","金额","使用公司", "使用部门", "使用人", "区域","存放地点", "管理员","所属公司","购入时间","供应商","使用期限","处理明细","","",""};
        String[] row5= {"", "", "", "","", "","","","","", "", "", "","", "","","","","","单据类型","处理时间","处理人","处理内容"};
        List<String[]> rowList = new ArrayList<>();
        rowList.add(row1);
        rowList.add(row2);
        rowList.add(row3);
        rowList.add(row4);
        rowList.add(row5);
        for (String[] rows : rowList) {
            row = sheet.createRow(rownum++);
            for (int i = 0; i < rows.length; i++) {
                cell = row.createCell(i);
                cell.setCellValue(rows[i]);
                if(rownum == 5 || rownum == 6){
                    cell.setCellStyle(ExcelStyle.styleCellNameAndGroundColor(wb));
                    if(rownum == 5 && i == 19){
                        cell.setCellStyle(ExcelStyle.styleAlignment(wb));
                    }
                    continue;
                }
                if(rownum == 3){
                    cell.setCellStyle(ExcelStyle.styleNotBorder(wb,4));
                    continue;
                }

                cell.setCellStyle(ExcelStyle.styleNotBorder(wb,1));
            }
        }
        //合并单元格
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 1));
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 2, 3));
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 4, 5));
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 6, 7));
        sheet.addMergedRegion(new CellRangeAddress(2, 2, 0, 1));
        sheet.addMergedRegion(new CellRangeAddress(2, 2, 2, 3));
        sheet.addMergedRegion(new CellRangeAddress(2, 2, 4, 5));
        sheet.addMergedRegion(new CellRangeAddress(2, 2, 6, 7));
        sheet.addMergedRegion(new CellRangeAddress(3, 3, 0, 8));
        //合并标题前部分
        for(int i = 0 ; i < 19 ;i++){
            sheet.addMergedRegion(new CellRangeAddress(4, 5, i, i));
        }
        //合并处理明细
        sheet.addMergedRegion(new CellRangeAddress(4, 4, 19, 22));

        List<String[]> rowsDate = (List<String[]>)rowsDataAndMergeRow.get("rows");
        //写入excel列表数据
        HSSFCellStyle hssfCellStyle = ExcelStyle.styleCellName(wb);
        for(int i = 0 ; i < rowsDate.size()  ; i++){
            row = sheet.createRow(rownum++);
            String[] cellData = rowsDate.get(i);
            for (int j = 0; j < cellData.length; j++) {
                cell = row.createCell( j);
                cell.setCellValue(cellData[j]);
                cell.setCellStyle(hssfCellStyle);
            }
        }
        //合并列表
        Map<Integer,Integer> needMerge = (Map<Integer,Integer>)rowsDataAndMergeRow.get("needMerge");
        List<Integer> needMergeList = (List<Integer>)rowsDataAndMergeRow.get("needMergeList");

        for(Integer rowNo : needMergeList){
            for(int i = 0 ; i < 19 ;i++){
                sheet.addMergedRegion(new CellRangeAddress(rowNo, rowNo+needMerge.get(rowNo)-1, i, i));
            }

        }
        return wb;
    }
    //构建列表数据
    private Map<String ,Object> buildRows(List<AssetHandleRecords> assetHandleRecord) {
        int mergeNo = 5;
        Map<String,String> countAssetNum = new HashMap<>();
        //总资产
        int assetTotal = assetHandleRecord.size();
        //总金额
        BigDecimal totalAmount = new BigDecimal("0");
        //正常使用
        int assetNormalTotal = 0;
        //已清理
        int clearAsset = 0;
        //处理列表数据
        List<String[]> datas = new ArrayList<>();
        //需要合并的行
        Map<Integer,Integer> needMergeRows = new HashMap<>();
        //存放需要合并的行集合
        List<Integer> needMergeList = new ArrayList<>();
        for(int i = 0 ; i < assetHandleRecord.size() ; i++){
            String[] rows = new String[23];
            AssetHandleRecords record = assetHandleRecord.get(i);
            if("清理报废".equals(record.getState())){
                clearAsset++;
            }else{
                assetNormalTotal++;
            }
            log.info("金额："+record.getAmount());
            totalAmount = totalAmount.add(new BigDecimal(StrUtil.isBlank(record.getAmount())  ? "0" : record.getAmount()));

            rows[0] = record.getState();
            rows[1] = record.getPhoto();
            rows[2] = record.getAssetCode();
            rows[3] = record.getAssetName();
            rows[4] = record.getAssetClassName();
            rows[5] = record.getSpecificationModel();
            rows[6] = record.getSnNumber();
            rows[7] = record.getUnitMeasurement();
            rows[8] = record.getAmount();
            rows[9] = record.getUseCompanyName();
            rows[10] = record.getUseDeptName();
            rows[11] = record.getUseUser();
            rows[12] = record.getAreaName();
            rows[13] = record.getStorageLocation();
            rows[14] = record.getAdmin();
            rows[15] = record.getCompanyName();
            rows[16] = record.getPurchaseTime();
            rows[17] = record.getSupplierName();
            rows[18] = record.getServiceLife();
            List<AssetHandleRecordDetailed> assetHandleRecordDetaileds = record.getAssetHandleRecordDetaileds();
            int datials = assetHandleRecordDetaileds.size();
            mergeNo += 1;
            if(datials > 1){
                needMergeRows.put(mergeNo,datials);
                needMergeList.add(mergeNo);
            }
            if(datials == 0){
                datas.add(rows);
                rows[19] = "";
                rows[20] = "";
                rows[21] = "";
                rows[22] = "";
                continue;
            }
            for (int j = 0 ; j <  datials  ; j++){
                AssetHandleRecordDetailed assetHandleRecordDetailed = assetHandleRecordDetaileds.get(j);
                if(j == 0){
                    rows[19] = assetHandleRecordDetailed.getHandType();
                    rows[20] = assetHandleRecordDetailed.getHandleTime();
                    rows[21] = assetHandleRecordDetailed.getHandleUser();
                    rows[22] = assetHandleRecordDetailed.getContent();
                    datas.add(rows);
                    continue;
                }
                mergeNo += 1;
                String[] rows2 = new String[23];
                rows2[0] = "";
                rows2[1] = "";
                rows2[2] = "";
                rows2[3] = "";
                rows2[4] = "";
                rows2[5] = "";
                rows2[6] = "";
                rows2[7] = "";
                rows2[8] = "";
                rows2[9] = "";
                rows2[10] = "";
                rows2[11] = "";
                rows2[12] ="";
                rows2[13] = "";
                rows2[14] = "";
                rows2[15] = "";
                rows2[16] = "";
                rows2[17] = "";
                rows2[18] = "";
                rows2[19] = assetHandleRecordDetailed.getHandType();
                rows2[20] = assetHandleRecordDetailed.getHandleTime();
                rows2[21] = assetHandleRecordDetailed.getHandleUser();
                rows2[22] = assetHandleRecordDetailed.getContent();
                datas.add(rows2);
            }

        }
        log.info("总金额："+totalAmount);
        countAssetNum.put("assetTotal",Integer.toString(assetTotal));
        countAssetNum.put("assetNormalTotal",Integer.toString(assetNormalTotal));
        countAssetNum.put("clearAsset",Integer.toString(clearAsset));
        countAssetNum.put("totalAmount",totalAmount.toString());
        Map<String,Object> rowsResult = new HashMap<>();
        rowsResult.put("rows",datas);
        rowsResult.put("needMerge",needMergeRows);
        rowsResult.put("statistics",countAssetNum);
        rowsResult.put("needMergeList",needMergeList);
        return  rowsResult;
    }

    /**
     * 查询资产类别
     * @param params
     * @param loginUser
     * @return
     */
    public List<AssetClassStatistics> getAssetClassStatistics(AssetClassParam params,LoginUser loginUser) {
        String userId = loginUser.getUserId();
        Integer isAllDataAuth = reportMapper.selectUserIsAllDataAuth(userId);
        //参数
        Map<String, Object> param = new HashMap<>();
        param.put("userId", userId);
        //是否有全部权限
        param.put("isAllDataAuth", Integer.toString(isAllDataAuth));
        param.put("TopCompanyId", loginUser.getCompanys().get(0).getCompanyId());
        param.put("companyId", params.getCompanyId());
        param.put("useDeptId", params.getDeptId());
        //如果没有全部权限查询各数据的权限
        if (isAllDataAuth == 2) {
            //类别
            List<String> classAuth = reportMapper.selectUserAuth(userId, 2);
            if (classAuth.size() > 0) {
                param.put("classAuth", classAuth);
            }
        }
        //查询结果
        List<AssetClassStatistics> assetClassStatistics = reportMapper.getAssetClassStatistics(param);
        //int maxLevel = assetClassStatistics.get(0).getTreecode().length();
        //计算总数
        for (int i=0; i < assetClassStatistics.size(); i++) {
            AssetClassStatistics entity = assetClassStatistics.get(i);
            Integer level = entity.getTreecode().split(",").length ;
            entity.setLevel(level.toString());
            Integer rootTotal = Integer.parseInt(StrUtil.isBlank(entity.getTotal())? "0" : entity.getTotal());
            BigDecimal rootAmount = new BigDecimal(StrUtil.isBlank(entity.getTotalAmount()) ? "0" : entity.getTotalAmount());
            int c= 0;
            for (AssetClassStatistics entity2 : assetClassStatistics) {
                c++;
                String treecode = entity2.getTreecode();
                String  total =  StrUtil.isBlank(entity2.getTotal())? "0" : entity2.getTotal();
                String  amount = StrUtil.isBlank(entity2.getTotalAmount()) ? "0" : entity2.getTotalAmount();
                //如果是根节点，加所有
                if (StrUtil.isBlank(entity.getPid()) && (!entity.getId().equals(entity2.getId())) && treecode.contains(entity.getId())){
                   System.out.println("根节点："+entity2.getName());
                    rootTotal += Integer.parseInt(total);
                    rootAmount = rootAmount.add(new BigDecimal(amount));
                    continue;
                }
                if ( (!entity.getId().equals(entity2.getId())) && StrUtil.isNotBlank(entity.getPid()) && treecode.contains(entity.getTreecode())  ){
                    System.out.println("非根节点："+c+entity2.getName());
                    rootTotal += Integer.parseInt(total);
                    rootAmount = rootAmount.add(new BigDecimal(amount));
                }
            }
            entity.setTotal(rootTotal.toString());
            entity.setTotalAmount(rootAmount.toString());
        }
        return assetClassStatistics;
    }
    /**
     * 查询维保到期
     *
     * @param
     * @return
     */
    public List<maintenanceXxpirationtReport> StatisticsOfMaintenanceExpiration(MaintenanceExpirationParam params,Integer pageNo,Integer PageSize ,LoginUser loginUser) {

        String userId = loginUser.getUserId();
        Integer isAllDataAuth = reportMapper.selectUserIsAllDataAuth(userId);

        //参数
        Map<String, Object> param = new HashMap<>();
        param.put("userId", userId);

        //是否有全部权限
        param.put("isAllDataAuth", Integer.toString(isAllDataAuth));
        param.put("TopCompanyId", loginUser.getCompanys().get(0).getCompanyId());
        param.put("startTime", params.getStartTime());
        param.put("endTime", params.getEndTime());
        param.put("search", params.getSearch());
        //如果没有全部权限查询各数据的权限
        if (isAllDataAuth == 2) {
            getUserAuth(userId, param);
        }
        if(pageNo != null && PageSize != null){
            PageHelper.startPage(pageNo, PageSize);
        }
        List<maintenanceXxpirationtReport> AssetList = reportMapper.StatisticsOfMaintenanceExpiration(param);
        for(maintenanceXxpirationtReport maintenanceXxpirationtReport : AssetList){
            handleAssetMaintenanceResult(maintenanceXxpirationtReport);
        }

        return AssetList;
    }
    //处理资产清单结果数据，查询结果code拼接在name
    private void handleAssetMaintenanceResult(maintenanceXxpirationtReport entity) {
        //设置区域
        String areaName = entity.getAreaName();
        if (StrUtil.isNotBlank(areaName)) {
            String[] areas = areaName.split("-");
            if(areas.length  == 2){
                entity.setAreaCode(areas[0]);
                entity.setAreaName(areas[1]);
            }

        }
        //设置使用公司
        String areaUseCompany = entity.getUseCompanyName();
        if (StrUtil.isNotBlank(areaUseCompany)) {
            String[] areaUseCompanys = areaUseCompany.split("-");
            if(areaUseCompanys.length  == 2){
                entity.setUseCompanyCode(areaUseCompanys[0]);
                entity.setUseCompanyName(areaUseCompanys[1]);
            }

        }
        //设置使用部门
        String areaUseDept = entity.getUseDeptName();
        if (StrUtil.isNotBlank(areaUseDept)) {
            String[] UseDepts = areaUseDept.split("-");
            if(UseDepts.length  == 2){
                entity.setUseDeptCode(UseDepts[0]);
                entity.setUseDeptName(UseDepts[1]);
            }

        }
        //设置所属公司
        String company = entity.getCompanyName();
        if (StrUtil.isNotBlank(company)) {
            String[] companys = company.split("-");
            if(companys.length == 2){
                entity.setCompanyCode(companys[0]);
                entity.setCompanyName(companys[1]);
            }

        }
    }
    /**
     * 查询首页头部统计信息（待审批、待签字、维保到期、报修资产数、待确认挑拨单）
     *
     * @return
     */
    public HomePageStatistics getHeaderData(LoginUser loginUser){
        String userId = loginUser.getUserId();
        Integer isAllDataAuth = reportMapper.selectUserIsAllDataAuth(userId);
        //参数
        Map<String, Object> param = new HashMap<>();
        param.put("userId", userId);
        //如果没有全部权限查询各数据的权限
        if (isAllDataAuth == 2) {
            getUserAuth(userId, param);
        }
        //是否有全部权限
        param.put("isAllDataAuth", Integer.toString(isAllDataAuth));
        param.put("TopCompanyId", loginUser.getCompanys().get(0).getCompanyId());
        //查询维保到期、报修资产数、待确认挑拨单统计
        HomePageStatistics expireAndRepairAndTransferCount = reportMapper.getExpireAndRepairAndTransferCount(param);
        //待审批
        int pendingApprovalCount = reportMapper.getPendingApprovalCount(param);
        expireAndRepairAndTransferCount.setPendingApprovalCount(Integer.toString(pendingApprovalCount));
        //待签字
        Integer toBeSignedCount = reportMapper.gettoBeSignedCount(userId);
        if(toBeSignedCount == null){
            toBeSignedCount = 0;
        }
        expireAndRepairAndTransferCount.setToBeSignedCount(Integer.toString(toBeSignedCount));
        return expireAndRepairAndTransferCount;
    }
    /**
     * 查询资产状况
     * @return
     *
     */
    public AssetStatus getAssetStatus(LoginUser loginUser){
        String userId = loginUser.getUserId();
        Integer isAllDataAuth = reportMapper.selectUserIsAllDataAuth(userId);
        //参数
        Map<String, Object> param = new HashMap<>();
        param.put("userId", userId);
        //如果没有全部权限查询各数据的权限
        if (isAllDataAuth == 2) {
            getUserAuth(userId, param);
        }
        //是否有全部权限
        param.put("isAllDataAuth", Integer.toString(isAllDataAuth));
        param.put("TopCompanyId", loginUser.getCompanys().get(0).getCompanyId());
        AssetStatus assetStatus = reportMapper.getAssetStatus(param);
        /*assetStatus.setFreeAmount(new BigDecimal(assetStatus.getFreeAmount()).toString());
        assetStatus.setUsedAmount(new BigDecimal(assetStatus.getUsedAmount()).toString());*/

        if(!assetStatus.getTotalCount().equals("0")){
            BigDecimal totalCount = new BigDecimal(assetStatus.getTotalCount());
            assetStatus.setUsePercent( new BigDecimal(assetStatus.getUsedCount()).divide(totalCount,2,BigDecimal.ROUND_UP).multiply(new BigDecimal("100")).toString());
            assetStatus.setFreePercent( new BigDecimal(assetStatus.getFreeCount()).divide(totalCount,2,BigDecimal.ROUND_UP).multiply(new BigDecimal("100")).toString());
        }
        return assetStatus;
    }

    /**
     * 查询所有资产状态数量
     * @param loginUser
     * @return
     */
    public AssetAllStatus getAssetStatusPer(LoginUser loginUser){
        String userId = loginUser.getUserId();
        Integer isAllDataAuth = reportMapper.selectUserIsAllDataAuth(userId);
        //参数
        Map<String, Object> param = new HashMap<>();
        param.put("userId", userId);
        //如果没有全部权限查询各数据的权限
        if (isAllDataAuth == 2) {
            getUserAuth(userId, param);
        }
        //是否有全部权限
        param.put("isAllDataAuth", Integer.toString(isAllDataAuth));
        param.put("TopCompanyId", loginUser.getCompanys().get(0).getCompanyId());
        AssetAllStatus assetStatus = reportMapper.getAssetStatusPer(param);

        return assetStatus;
    }

    /**
     * 查询分类统计
     * @param loginUser
     * @return
     */
    public HomePageStatisticsResult getAssetTypeSum(LoginUser loginUser,String companyId){
        String userId = loginUser.getUserId();
        Integer isAllDataAuth = reportMapper.selectUserIsAllDataAuth(userId);
        //参数
        Map<String, Object> param = new HashMap<>();
        param.put("userId", userId);
        param.put("company", companyId);
        //如果没有全部权限查询各数据的权限
        if (isAllDataAuth == 2) {
            getUserAuth(userId, param);
        }
        //是否有全部权限
        param.put("isAllDataAuth", Integer.toString(isAllDataAuth));
        param.put("TopCompanyId", loginUser.getCompanys().get(0).getCompanyId());
        List<Map<String, Object>> assetTypeSum = reportMapper.getAssetTypeSum(param);
        //组装报表格式
        HomePageStatisticsResult result = new HomePageStatisticsResult();
        String[] xAxis = null;
        String[] series = null;
        String[] series1 = null;
        if(assetTypeSum.size() == 0){
            List<Map<String, String>> enableAssetType = reportMapper.getEnableAssetType(param);
            int arraySize = enableAssetType.size();
            xAxis = new String[arraySize];
            series = new String[arraySize];
            series1 = new String[arraySize];
            for(int i = 0 ; i< enableAssetType.size() ; i++){
                Map<String, String> map = enableAssetType.get(i);
                xAxis[i] = map.get("name");
                series[i] = "0";
                series1[i] = "0";
            }
        }else{
            int arraySize = assetTypeSum.size();
            xAxis = new String[arraySize];
            series = new String[arraySize];
            series1 = new String[arraySize];
            for(int i = 0 ; i< assetTypeSum.size() ; i++){
                Map<String, Object> map = assetTypeSum.get(i);
                xAxis[i] = map.get("name").toString();
                series[i] = new BigDecimal((Long) map.get("sumTotal")).toString();
                BigDecimal amountTotal = (BigDecimal)map.get("amountTotal");
                series1[i] = amountTotal == null ? "0" : amountTotal.toString();
            }

        }
        result.setxAxis(xAxis);
        result.setSeries(series);
        result.setSeries1(series1);
        result.setyAxirs(null);
      return result;
    }

    /**
     * 查询耗材领用情况
     * @param params
     * @param loginUser
     */
    public HcStatisticsResult getHcUseStatus(UseStatusParam params,LoginUser loginUser){
        /**
         * 横坐标
         */
        String[] dateAxis= getDate(Integer.parseInt(params.getYearNum()));
        String userId = loginUser.getUserId();
        Integer isAllDataAuth = reportMapper.selectUserIsAllDataAuth(userId);
        //参数
        Map<String, Object> param = new HashMap<>();
        param.put("userId", userId);
        param.put("useOrg", params.getCompanyId());
        //如果没有全部权限查询各数据的权限
        if (isAllDataAuth == 2) {
            //仓库
            List<String> wareHouseAuth = reportMapper.selectUserAuth(userId, 4);
            if (wareHouseAuth.size() > 0) {
                param.put("wareHouseAuth", wareHouseAuth);
            }
        }
        //是否有全部权限
        param.put("isAllDataAuth", Integer.toString(isAllDataAuth));
        param.put("TopCompanyId", loginUser.getCompanys().get(0).getCompanyId());
        //查询耗材
        List<Map<String, Object>> hcUseStatus = reportMapper.getHcUseStatus(param);
        //查询分类
        List<Map<String, String>> hcType = reportMapper.getHcType(loginUser.getCompanys().get(0).getCompanyId());
        //组装数据
        HcStatisticsResult result = BuildHcStatisticsResultForReport(dateAxis, hcUseStatus, hcType);
        return result;
    }

    private HcStatisticsResult BuildHcStatisticsResultForReport(String[] dateAxis, List<Map<String, Object>> hcUseStatus, List<Map<String, String>> hcType) {
        //x轴
        HcStatisticsResult result = new HcStatisticsResult();

        //y轴
        String[] yAxirs = new String[hcType.size()];
        //seriesList
        List<HcStatisticsSeriesList> seriesList = new ArrayList<>();
        //seriesList1
        List< HcStatisticsSeriesList> seriesList1 = new ArrayList<>();
        int i = 0;
        for(Map<String, String> type : hcType){
            String name = type.get("name");
            String id = type.get("id");
            yAxirs[i++] = name;
            // //seriesList
            HcStatisticsSeriesList seriesEntity = new HcStatisticsSeriesList();
            seriesEntity.setName(name);
            seriesEntity.setStack("数量");
            HcStatisticsSeriesList seriesEntity1 = new HcStatisticsSeriesList();
            seriesEntity1.setName(name);
            seriesEntity1.setStack("金额");
            String[] data = new  String[dateAxis.length];
            String[] data1 = new  String[dateAxis.length];
            for(int k = 0 ; k < dateAxis.length ; k++){
                data[k] = "0";
                data1[k] = "0";
                for (int j = 0 ; j < hcUseStatus.size() ; j++){
                    Map<String, Object> stringObjectMap = hcUseStatus.get(j);
                    if(stringObjectMap.get("typeId").equals(id) && stringObjectMap.get("time").equals(dateAxis[k]) ){
                        data[k] = stringObjectMap.get("num").toString();
                        data1[k] = stringObjectMap.get("amount").toString();
                        break;
                    }
                }
            }

            seriesEntity.setData(data);
            seriesEntity1.setData(data1);
            seriesList.add(seriesEntity);
            seriesList1.add(seriesEntity1);
        }
        result.setxAxis(dateAxis);
        result.setyAxirs(yAxirs);
        result.setSeriesList(seriesList);
        result.setSeriesList1(seriesList1);
        return result;
    }

    /**
     * 获取时间轴
     * @param yearNum 近几月
     * @return
     */
    public  String[] getDate(int yearNum){
        int j = 0;
        String[] date = new String[yearNum];
        for(int i = yearNum-1 ; i >= 0 ; i--){
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MONTH, -i);
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH)+1;
            if(month < 10){
                date[j++] = year+"-0"+month;
            }else{
                date[j++] = year+"-"+month;
            }

        }

        return  date;
    }

    /**
     * 查询固资使用情况
     * @param params
     * @param loginUser
     * @return
     */
    public HomePageStatisticsResult getAssetUseStatus(UseStatusParam params,LoginUser loginUser) {
        HomePageStatisticsResult result = new HomePageStatisticsResult();
        /**
         * 横坐标
         */
        String[] dateAxis = getDate(Integer.parseInt(params.getYearNum()));
        result.setxAxis(dateAxis);
        String userId = loginUser.getUserId();
        Integer isAllDataAuth = reportMapper.selectUserIsAllDataAuth(userId);
        //参数
        Map<String, Object> param = new HashMap<>();
        param.put("userId", userId);
        param.put("useCompanyId", params.getCompanyId());
        //如果没有全部权限查询各数据的权限
        if (isAllDataAuth == 2) {
            getUserAuth(userId, param);
        }
        //是否有全部权限
        param.put("isAllDataAuth", Integer.toString(isAllDataAuth));
        param.put("TopCompanyId", loginUser.getCompanys().get(0).getCompanyId());
        //查询固资统计
        List<Map<String, Object>> assetUseStatus = reportMapper.getAssetUseStatus(param);
        //组装数据
        //数量
        String[] series = new String[dateAxis.length];
        //金额
        String[] series1 = new String[dateAxis.length];
        for(int i = 0 ; i < dateAxis.length ; i++){
            series[i] = "0";
            series1[i] = "0";
            for(Map<String, Object> map : assetUseStatus){
                if(map.get("time").equals(dateAxis[i])){
                    series[i] = map.get("total").toString();
                    series1[i] =  map.get("amount") == null ? "0" : map.get("amount").toString();
                    break;
                }
            }
        }
        result.setSeries(series);
        result.setSeries1(series1);
        result.setyAxirs(null);
        return result;
    }
}
